<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="社区" prop="communityId">
        <el-select
            v-model="queryParams.communityId"
            placeholder="请选择社区"
            clearable
            filterable
        >
          <el-option v-for="c in community" :label="c.name || c.communityId" :value="c.communityId"/>
        </el-select>
      </el-form-item>
      <el-form-item label="商品区域" prop="areaName">
        <el-input
            v-model="queryParams.areaName"
            placeholder="请输入商品区域"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商铺编号" prop="shopNo">
        <el-input
            v-model="queryParams.shopNo"
            placeholder="请输入商铺编号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所在楼层" prop="floorNo">
        <el-input
            v-model="queryParams.floorNo"
            placeholder="请输入所在楼层"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="建筑面积" prop="buildingArea">
        <el-input
            v-model="queryParams.buildingArea"
            placeholder="请输入建筑面积"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="使用面积" prop="usableArea">
        <el-input
            v-model="queryParams.usableArea"
            placeholder="请输入使用面积"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="公摊面积" prop="publicArea">
        <el-input
            v-model="queryParams.publicArea"
            placeholder="请输入公摊面积"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['comsys:shop:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['comsys:shop:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['comsys:shop:remove']"
        >批量删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['comsys:shop:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Upload"
            @click="handleImport"
            v-hasPermi="['comsys:shop:import']"
        >导入
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="shopList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="商铺ID" align="center" prop="shopId"/>
      <el-table-column label="社区" align="center" prop="communityId">
        <template #default="scope">
          <span>{{ getCommunityName(scope.row.communityId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品区域" align="center" prop="areaName"/>
      <el-table-column label="商铺编号" align="center" prop="shopNo"/>
      <el-table-column label="所在楼层" align="center" prop="floorNo"/>
      <el-table-column label="建筑面积" align="center" prop="buildingArea">
        <template #default="scope">
          <span>{{ scope.row.buildingArea ? scope.row.buildingArea + '㎡' : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="使用面积" align="center" prop="usableArea">
        <template #default="scope">
          <span>{{ scope.row.usableArea ? scope.row.usableArea + '㎡' : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="房屋类型" align="center" prop="houseType"/>
      <el-table-column label="商铺状态" align="center" prop="shopStatus"/>
      <el-table-column label="公摊面积" align="center" prop="publicArea">
        <template #default="scope">
          <span>{{ scope.row.publicArea ? scope.row.publicArea + '㎡' : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="description"/>
      <el-table-column label="商铺图片" align="center" prop="images">
        <template #default="scope">
          <div v-if="scope.row.images" class="table-image-container">
            <el-image
                :src="scope.row.images"
                :preview-src-list="[scope.row.images]"
                class="table-preview-item"
                fit="cover"
                lazy
            />
          </div>
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['comsys:shop:edit']">
            修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['comsys:shop:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改商铺管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="shopRef" :model="form" :rules="rules" label-width="80px">
        <!-- 社区下拉框 -->
        <el-form-item label="社区">
          <el-select v-model="form.communityId" placeholder="请选择社区" clearable>
            <el-option v-for="c in community" :label="c.name || c.communityId" :value="c.communityId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品区域" prop="areaName">
          <el-input v-model="form.areaName" placeholder="请输入商品区域"/>
        </el-form-item>
        <el-form-item label="商铺编号" prop="shopNo">
          <el-input v-model="form.shopNo" placeholder="请输入商铺编号"/>
        </el-form-item>
        <el-form-item label="所在楼层" prop="floorNo">
          <el-input v-model="form.floorNo" placeholder="请输入所在楼层"/>
        </el-form-item>
        <el-form-item label="建筑面积" prop="buildingArea">
          <el-input v-model="form.buildingArea" placeholder="请输入建筑面积"/>
        </el-form-item>
        <el-form-item label="商铺状态" prop="shopStatus">
            <el-select v-model="form.shopStatus" placeholder="请选择或输入商铺状态" clearable filterable allow-create>
              <el-option label="有效" value="有效"></el-option>
              <el-option label="空置" value="空置"></el-option>
            </el-select>
          </el-form-item>
        <el-form-item label="公摊面积" prop="publicArea">
          <el-input v-model="form.publicArea" placeholder="请输入公摊面积"/>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="图片(JSON数组)" prop="images">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:8080/upload/img"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="headers"
          >
            <img v-if="form.images" :src="form.images" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Shop">
import {listShop, getShop, delShop, addShop, updateShop} from "@/api/comsys/shop"
import {Plus} from "@element-plus/icons-vue";
import {getToken} from "@/utils/auth.js";
import {ElMessage} from "element-plus";
import request from '@/utils/request'

const {proxy} = getCurrentInstance()

const shopList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const router = useRouter()

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    communityId: null,
    areaName: null,
    shopNo: null,
    floorNo: null,
    buildingArea: null,
    usableArea: null,
    houseType: null,
    houseStatus: null,
    publicArea: null,
    description: null,
    images: null,
  },
  rules: {}
})

const {queryParams, form, rules} = toRefs(data)

/** 查询商铺管理列表 */
function getList() {
  loading.value = true
  listShop(queryParams.value).then(response => {
    shopList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    shopId: null,
    communityId: null,
    areaName: null,
    shopNo: null,
    floorNo: null,
    buildingArea: null,
    usableArea: null,
    houseType: null,
    houseStatus: null,
    shopStatus: null,
    publicArea: null,
    description: null,
    images: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("shopRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.shopId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  // 若查询区已选择社区，则带入新增弹窗
  if (queryParams.value.communityId) {
    form.value.communityId = queryParams.value.communityId
  }
  open.value = true
  title.value = "添加商铺管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _shopId = row.shopId || ids.value
  getShop(_shopId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改商铺管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["shopRef"].validate(valid => {
    if (valid) {
      if (form.value.shopId != null) {
        updateShop(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addShop(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _shopIds = row.shopId || ids.value
  proxy.$modal.confirm('是否确认删除商铺管理编号为"' + _shopIds + '"的数据项？').then(function () {
    return delShop(_shopIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('comsys/shop/export', {
    ...queryParams.value
  }, `shop_${new Date().getTime()}.xlsx`)
}

/** 导入按钮操作 */
function handleImport() {
  router.push({path: '/comsys/shop/import'})
}

const headers = ref({Authorization: "Bearer " + getToken()})
// 图片上传
const handleAvatarSuccess = (
    response
) => {
  ElMessage.success("上传成功")
  form.value.images = response.msg
  // console.log(response)
}

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

const community = ref([])
//显示社区id下拉框
const initCommunity = () => {
  request({
    url: `/communityVo/getCommunityVoNameById`,
    method: 'get'
  }).then((response) => {
    community.value = response.data;
  })
}

// 映射社区名称
const communityMap = ref({})
const getCommunityName = (cid) => {
  if (cid == null) return '-'
  const key = typeof cid === 'string' ? cid : String(cid)
  return communityMap.value[key] || communityMap.value[cid] || cid
}

watch(community, (list) => {
  const map = {}
  ;(list || []).forEach(c => {
    if (c && c.communityId != null) {
      map[c.communityId] = c.name || c.communityName || c.communityId
    }
  })
  communityMap.value = map
})
initCommunity()
getList()
</script>

<style scoped>
.avatar-uploader, .avatar-uploader.el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}
.avatar-uploader:hover { border-color: var(--el-color-primary); }
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  object-fit: cover;
  display: block;
}
</style>
